<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px">
      <el-form-item label="Name" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder=""
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="Industry" prop="industry">
        <el-input
          v-model="queryParams.industry"
          placeholder=""
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!--<el-form-item-->
        <!--label="staff"-->
        <!--prop="createUserId"-->
        <!--v-hasPermi="['system:client:staff']">-->
        <!--<el-input-->
          <!--v-model="queryParams.createUserId"-->
          <!--placeholder=""-->
          <!--clearable-->
          <!--@keyup.enter.native="handleQuery"-->
        <!--/>-->
      <!--</el-form-item>-->
      <el-form-item
        v-hasPermi="['system:client:staff']"
        prop="createUserId"
        label="BD Staff">
        <el-select
          clearable
          filterable
          remote
          :remote-method="filterVmModel"
          v-selectLoadmore="loadMore"
          v-model="queryParams.createUserId"
          :loading="loadingStaff"
          placeholder="">
          <el-option
            v-for="item in userOptions"
            :key="item.userName"
            :label="item.userName"
            :value="item.userName"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item
        v-hasPermi="['system:client:staff']"
        prop="createUserId"
        label="Staff">
        <el-select
          clearable
          filterable
          remote
          :remote-method="filterVmModel"
          v-selectLoadmore="loadMore"
          v-model="queryParams.assId"
          :loading="loadingStaff"
          placeholder="">
          <el-option
            v-for="item in userOptions"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery">Search</el-button>
        <!--<el-button v-if="false" icon="el-icon-refresh" size="mini" @click="resetQuery">Reset</el-button>-->
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >Add</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      border
      v-loading="loading"
      :data="clientList"
      @selection-change="handleSelectionChange">
      <el-table-column
        width="120px"
        label="Action"
        align="center"
        class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >edit</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handlePositionUpdate(scope.row)"
          >position</el-button>
          <el-dropdown
            size="mini"
            @command="(command) => handleCommand(command, scope.row)"
            v-hasPermi="['system:client:staff']"
          >
            <el-button size="mini" type="text" icon="el-icon-d-arrow-right">More</el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                command="handleAssign"
                icon="el-icon-circle-check"
                                v-hasPermi="['system:client:staff']">Assign</el-dropdown-item>
              <el-dropdown-item
                command="handleHistory"
                icon="el-icon-user"
              v-hasPermi="['system:client:staff']">History</el-dropdown-item>
              <el-dropdown-item
                command="handleDelete"
                icon="el-icon-delete"
                v-hasPermi="['system:client:del']">Del</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <!--<el-button-->
            <!--size="mini"-->
            <!--type="text"-->
            <!--icon="el-icon-edit"-->
            <!--v-hasPermi="['system:client:staff']"-->
            <!--@click="handleAssign(scope.row)"-->
          <!--&gt;Assign</el-button>-->
          <!--<el-button-->
            <!--size="mini"-->
            <!--type="text"-->
            <!--icon="el-icon-edit"-->
            <!--v-hasPermi="['system:client:staff']"-->
            <!--@click="handleHistory(scope.row)"-->
          <!--&gt;History</el-button>-->
          <!--<el-dropdown placement="left-start">-->
            <!--<el-button-->
              <!--size="mini"-->
              <!--type="text"-->
              <!--v-hasPermi="['system:client:staff']">-->
              <!--History-->
            <!--</el-button>-->
            <!--<el-dropdown-menu slot="dropdown">-->
              <!--<el-dropdown-item v-for="(item,index) in scope.row.assList">-->
                <!--<el-table-->
                  <!--border-->
                  <!--:data="clientList">-->
                  <!--<el-table-column label="Assign Name" align="left" prop="userName">-->
                    <!--{{item.userName}}-->
                  <!--</el-table-column>-->
                  <!--<el-table-column label="Create Date" align="left" prop="createTime">-->
                    <!--<template slot-scope="scope">-->
                      <!--<span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>-->
                    <!--</template>-->
                  <!--</el-table-column>-->
                  <!--<el-table-column label="Create By" align="left" prop="createBy">-->
                    <!--{{item.createBy}}-->
                  <!--</el-table-column>-->
                <!--</el-table>-->
              <!--</el-dropdown-item>-->
            <!--</el-dropdown-menu>-->
          <!--</el-dropdown>-->
          <!--<br>-->
          <!--<el-button-->
            <!--size="mini"-->
            <!--type="text"-->
            <!--icon="el-icon-delete"-->
            <!--v-hasPermi="['system:client:del']"-->
            <!--@click="handleDelete(scope.row)"-->
            <!--&gt;Del</el-button>-->
        </template>
      </el-table-column>
      <el-table-column
        v-if="$auth.hasPermi('system:client:staff')"
        label="BD Staff"
        align="left"
        prop="createUserId" />
      <el-table-column
        v-if="$auth.hasPermi('system:client:staff')"
        label="Staff"
        align="left"
        prop="assName" />
      <el-table-column show-overflow-tooltip label="Name" align="left" prop="name" />
      <el-table-column show-overflow-tooltip label="Contact1" align="left" prop="contact1" />
      <el-table-column show-overflow-tooltip label="Address" align="left" prop="address" />
      <el-table-column show-overflow-tooltip label="Co-Size" align="left" prop="coSize" />
      <el-table-column show-overflow-tooltip label="Po-Size" align="left" prop="poSize" />
      <el-table-column show-overflow-tooltip label="Tel" align="left" prop="tel11" />
      <el-table-column
        width="110px"
        label="T&C uploaded"
        align="left"
        prop="email1">
        <template slot-scope="scope">
          <span v-if="scope.row.filePath != null
          && scope.row.filePath != ''
          && scope.row.filePath != undefined">Yes</span>
          <span v-else></span>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip label="Create Date" align="left" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog
      title="Assignment History"
      :visible.sync="openHistory"
      width="800px"
      append-to-body
    >
      <el-table
        :data="assList"
        style="margin-top: 0px;">
        <el-table-column label="Assign Name" align="left" prop="userName" />
        <el-table-column label="Create Date" align="left" prop="createTime">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="Create By" align="left" prop="createBy"/>
      </el-table>

      <pagination
        v-show="totalAss>0"
        :total="totalAss"
        :page.sync="queryParamsAss.pageNum"
        :limit.sync="queryParamsAss.pageSize"
        @pagination="getAssList"
      />
    </el-dialog>

    <el-dialog
      title="Assignment"
      :visible.sync="open"
      width="800px"
      append-to-body
    >
      <el-form
        :model="queryParamsUser"
        ref="queryFormUser"
        size="small"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
        style="margin-top: 20px;">
        <!--form表单中只有一个输入框的时候，在输入框中按下回车就是提交该表单并且会自动刷新页面。-->
        <el-form-item
          label="Name"
          prop="userName">
          <el-input
            v-model="queryParamsUser.userName"
            placeholder=""
            clearable
            @keyup.enter.native="handleUserQuery"
          />
        </el-form-item>
        <el-form-item
          label="Name"
          prop="userName"
          style="display: none;">
          <el-input
            v-model="queryParamsUser.userName"
            placeholder=""
            clearable
            @keyup.enter.native="handleUserQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleUserQuery">Search</el-button>
        </el-form-item>
      </el-form>
      <el-table
        :data="candidateList"
        style="margin-top: 0px;">
        <el-table-column
          width="60px"
          label="action"
          align="left"
          class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-check"
              @click="handleAddUserCand(scope.row)"
            >Assign</el-button>
          </template>
        </el-table-column>
        <el-table-column label="name" align="center" key="userName" prop="userName" />
        <el-table-column label="nick" align="center" key="nickName" prop="nickName" />
        <el-table-column label="phone" align="center" key="phonenumber" prop="phonenumber" />
      </el-table>

      <pagination
        v-show="totalUser>0"
        :total="totalUser"
        :page.sync="queryParamsUser.pageNum"
        :limit.sync="queryParamsUser.pageSize"
        @pagination="getCandList"
      />
    </el-dialog>

  </div>
</template>

<script>
import { listClient, getClient, delClient, addClient, updateClient } from "@/api/system/client";
import { listUser, getUser, delUser, addUser, updateUser, resetUserPwd, changeUserStatus} from "@/api/system/user";
import { listAss, getAss, delAss, addAss, updateAss } from "@/api/system/ass";

export default {
  name: "Client",
  data() {
    return {
      openHistory: false,
      assList: [],
      queryParamsAss: {
        pageNum: 1,
        pageSize: 10,
        cId: null
      },
      totalAss: 0,
      loadingStaff: false,
      userOptions: [],
      userList: [],
      userTotal: 0,
      // 日期范围
      dateRange: [],
      candidateList: [],
      queryParamsUser: {
        pageNum: 1,
        pageSize: 10,
        userName: null
      },
      totalUser: 0,
      itemForm: {},
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      clientList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        clientCode: null,
        createTime: null,
        createUserId: null,
        assId: null,
        name: null,
        industry: null,
        busiNature: null,
        address: null,
        coSize: null,
        contact1: null,
        pos1: null,
        tel11: null,
        tel12: null,
        email1: null,
        contact2: null,
        pos2: null,
        tel21: null,
        tel22: null,
        email2: null,
        lastAssignee: null,
        website: null,
        updateTime: null,
        updateUserId: null,
      },
      // 表单参数
      form: {}
    };
  },
  created() {
    // this.getCandList();
    this.getUserList();
    this.getList();
  },
  methods: {
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleAssign":
          this.handleAssign(row);
          break;
        case "handleHistory":
          this.handleHistory(row);
          break;
        case "handleDelete":
          this.handleDelete(row);
          break;
        default:
          break;
      }
    },
    loadMore(firstTag) {
      this.queryParamsUser.pageNum++;
      this.getUserList();
    },
    filterVmModel (value) {
      this.loadingStaff = true;
      console.log("=======================" + value)
      this.queryParamsUser.userName = value;
      this.queryParamsUser.pageNum = 1;
      this.getUserList();
    },
    getUserList() {
      //获取用户Staff
      listUser(this.addDateRange(this.queryParamsUser, this.dateRange)).then(response => {
          this.userList = response.rows;
          if (this.queryParamsUser.pageNum == 1) {
            this.userOptions = [];
            this.userOptions.push(...this.userList);
          } else {
            this.userOptions.push(...this.userList);
          }
          this.userTotal = response.total;
        }
      ).finally(f => {
        this.loadingStaff = false;
      });
    },
    handleAddUserCand(row){
      //分配任务
      this.$modal.loading("loading...");
      // this.itemForm.createUserId = row.userName;
      this.itemForm.type = 1;
      this.itemForm.assId = row.userId;
      updateClient(this.itemForm).then(response => {
        this.$modal.msgSuccess("success");
        this.getList();
      }).catch(err => {
        this.$modal.msgError("Fail,Please Again");
      }).finally(f => {
        this.open = false;
        this.$modal.closeLoading();
      });
    },
    getAssList() {
      this.$modal.loading("loading...");
      listAss(this.queryParamsAss).then(response => {
        this.assList = response.rows;
        this.totalAss = response.total;
      }).finally(f => {
        this.$modal.closeLoading();
      });
    },
    handleHistory(row) {
      this.openHistory = true;
      this.queryParamsAss.cId = row.id;
      this.queryParamsAss.pageNum = 1;
      this.queryParamsAss.pageSize = 10;
      this.getAssList();
    },
    handleAssign(row) {
      this.open = true;
      this.itemForm = row;
    },
    getCandList() {
      // this.loading = true;
      listUser(this.queryParamsUser).then(response => {
        this.candidateList = response.rows;
        this.totalUser = response.total;
        // this.loading = false;
      });
    },
    handleUserQuery() {
      this.queryParamsUser.pageNum = 1;
      this.getCandList();
    },
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true;
      listClient(this.queryParams).then(response => {
        this.clientList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        clientCode: null,
        createTime: null,
        createUserId: null,
        name: null,
        industry: null,
        busiNature: null,
        address: null,
        coSize: null,
        contact1: null,
        pos1: null,
        tel11: null,
        tel12: null,
        email1: null,
        contact2: null,
        pos2: null,
        tel21: null,
        tel22: null,
        email2: null,
        lastAssignee: null,
        website: null,
        updateTime: null,
        updateUserId: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      const obj = { path: "/system/client/clientAdd" };
      this.$tab.closeOpenPage(obj);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const id = row.id || this.ids
      const obj = { path: "/system/client/clientAdd", name: "ClientAdd" };
      this.$tab.closePage(obj);
      setTimeout(()=> {
        this.$router.push({path:'/system/client/clientAdd',query: {id}})
      }, 300);
    },
    handlePositionUpdate(row){
      const id = row.id || this.ids
      const obj = { path: "/system/position/index", name: "positionIndex" };
      this.$tab.closePage(obj);
      setTimeout(()=> {
        this.$router.push({path:'/system/position/index',query: {id}})
      }, 300);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateClient(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addClient(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除【请填写功能名称】编号为"' + ids + '"的数据项？').then(function() {
        return delClient(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/client/export', {
        ...this.queryParams
      }, `client_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
